package rinpu.springtest.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import rinpu.springtest.pojo.entity.Permission;
import rinpu.springtest.pojo.entity.SecurityUser;
import rinpu.springtest.pojo.entity.User;
import rinpu.springtest.mapper.UserMapper;
import rinpu.springtest.service.RoleService;
import rinpu.springtest.service.UserService;

import java.util.HashSet;
import java.util.List;

/**
 * @Author Rin_pu
 * @Date 2025/9/16 21:03
 * @Description UserServiceImpl
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService, UserDetailsService {

    @Resource
    private RoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = baseMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, username));
        if (user == null) {
            throw new RuntimeException("用户名不存在");
        }
        SecurityUser loginUser = new SecurityUser();
        loginUser.setUser(user);
        loginUser.setPermissions(new HashSet<>(this.findperms(user.getId())));
        return loginUser;
    }

    @Override
    public List<Permission> findperms(Long id) {
        return roleService.getPermissionByUserId(id);
    }
}
